import React, {useCallback, useEffect, useState} from 'react'
import {Badge, Button, Card, Col, Descriptions, Empty, message, Row, Switch, Tag, Typography} from 'antd'
import {CheckCircle, Clock, Code, Database, Link, Server, User, XCircle} from 'lucide-react'
import type {DataSourceTreeNode} from '@/components/business/DataSourceTree/types'
import {useDataSourceStore} from '@/stores/dataSourceStore'
import {dataSourceApi} from '@/services/api/dataSource'
import type {CatalogVo} from '@/types/api'

const { Title, Text } = Typography

const CatalogPanel: React.FC<{ node: DataSourceTreeNode }> = ({ node }) => {
  const catalogName = (node.catalogName ?? node.title) as string
  const { testConnection, syncCatalog, setEnabled, updateSystemCode } = useDataSourceStore()
  const [msgApi, contextHolder] = message.useMessage()
  const [enabled, setEnabledLocal] = React.useState<boolean>(!!node.enabled)
  const [systemCode, setSystemCodeLocal] = React.useState<string>('')
  const [catalogDetail, setCatalogDetail] = useState<CatalogVo | null>(null)
  const [loadingDetail, setLoadingDetail] = useState(false)

  const notify = useCallback((content: string, type: 'success' | 'error' = 'success') => {
    msgApi.open({ type, content })
  }, [msgApi])

  useEffect(() => {
    let mounted = true
    const fetchCatalog = async () => {
      setLoadingDetail(true)
      try {
        const detail = await dataSourceApi.getCatalog(catalogName)
        if (mounted) setCatalogDetail(detail)
      } finally {
        if (mounted) setLoadingDetail(false)
      }
    }
    setCatalogDetail(null)
    if (catalogName) fetchCatalog()
    return () => { mounted = false }
  }, [catalogName])

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      {contextHolder}

      {/* 标题卡片 */}
      <Card style={{ border: 'none', background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Database size={28} style={{ color: '#ffffff', marginRight: 12 }} />
            <div>
              <Title level={3} style={{ color: '#ffffff', margin: 0, textShadow: '0 2px 4px rgba(0,0,0,0.3)' }}>
                {catalogName}
              </Title>
              <Text style={{ color: 'rgba(255, 255, 255, 0.85)', fontSize: 14 }}>
                数据源目录管理
              </Text>
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <Badge
              status={enabled ? 'success' : 'error'}
              text={
                <span style={{ color: '#ffffff', fontSize: 12 }}>
                  {enabled ? '已启用' : '已禁用'}
                </span>
              }
            />
            {catalogDetail?.databaseType && (
              <Tag style={{ background: 'rgba(255, 255, 255, 0.2)', border: 'none', color: '#ffffff' }}>
                {catalogDetail.databaseType}
              </Tag>
            )}
              <Switch
                  checked={enabled}
                  onChange={async (v) => {
                      setEnabledLocal(v)
                      await setEnabled({ level: 'catalog', catalogName, enabled: v })
                  }}></Switch>
              <Button
                  type="primary"
                  icon={<Database size={14} />}
                  onClick={async () => {
                      await syncCatalog(catalogName)
                      notify('目录同步完成')
                  }}
                  block
              >
                  同步目录
              </Button>
          </div>
        </div>
      </Card>


      {/* 目录详情 */}
      <Card
        title={
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Database size={16} style={{ marginRight: 8, color: '#1890ff' }} />
            目录详情
            {catalogDetail && (
              <Badge
                count="已连接"
                style={{ backgroundColor: '#52c41a', marginLeft: 12 }}
              />
            )}
          </div>
        }
        loading={loadingDetail}
        styles={{ body: { maxHeight: '60vh', overflow: 'auto' } }}
      >
        {catalogDetail ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
              {/* 连接状态 */}
              <div>
                  <Title level={5} style={{ color: '#1d2129', marginBottom: 12 }}>
                      <CheckCircle size={16} style={{ marginRight: 6 }} />
                      连接状态
                  </Title>
                  <Row gutter={[12, 12]}>
                      {catalogDetail.serverConnected !== undefined && (
                          <Col xs={24} sm={8}>
                              <Card size="small" style={{ textAlign: 'center' }}>
                                  <div style={{ marginBottom: 8 }}>
                                      <Server size={24} style={{ color: catalogDetail.serverConnected ? '#52c41a' : '#ff4d4f' }} />
                                  </div>
                                  <Text strong>服务器连接</Text>
                                  <div style={{ marginTop: 4 }}>
                                      <Tag color={catalogDetail.serverConnected ? 'success' : 'error'}>
                                          {catalogDetail.serverConnected ? '成功' : '失败'}
                                      </Tag>
                                  </div>
                                  {catalogDetail.serverConnectedDt && (
                                      <div style={{ marginTop: 4 }}>
                                          <Text type="secondary" style={{ fontSize: 11 }}>
                                              <Clock size={10} style={{ marginRight: 2 }} />
                                              {catalogDetail.serverConnectedDt}
                                          </Text>

                                      </div>
                                  )}
                                  <Button
                                      icon={<Server size={14} />}
                                      onClick={async () => {
                                          const ok = await testConnection(catalogName, 'server')
                                          notify(ok ? '服务器连接成功' : '服务器连接失败', ok ? 'success' : 'error')
                                      }}
                                  >
                                      测试
                                  </Button>
                              </Card>
                          </Col>
                      )}

                      {catalogDetail.jdbcConnected !== undefined && (
                          <Col xs={24} sm={8}>
                              <Card size="small" style={{ textAlign: 'center' }}>
                                  <div style={{ marginBottom: 8 }}>
                                      <Database size={24} style={{ color: catalogDetail.jdbcConnected ? '#52c41a' : '#ff4d4f' }} />
                                  </div>
                                  <Text strong>JDBC连接</Text>
                                  <div style={{ marginTop: 4 }}>
                                      <Tag color={catalogDetail.jdbcConnected ? 'success' : 'error'}>
                                          {catalogDetail.jdbcConnected ? '成功' : '失败'}
                                      </Tag>
                                  </div>
                                  {catalogDetail.jdbcConnectedDt && (
                                      <div style={{ marginTop: 4 }}>
                                          <Text type="secondary" style={{ fontSize: 11 }}>
                                              <Clock size={10} style={{ marginRight: 2 }} />
                                              {catalogDetail.jdbcConnectedDt}
                                          </Text>
                                      </div>
                                  )}
                                  <Button
                                      icon={<Database size={14} />}
                                      onClick={async () => {
                                          const ok = await testConnection(catalogName, 'jdbc')
                                          notify(ok ? 'JDBC连接成功' : 'JDBC连接失败', ok ? 'success' : 'error')
                                      }}
                                  >
                                      测试JDBC
                                  </Button>
                              </Card>
                          </Col>
                      )}

                      {catalogDetail.dorisConnected !== undefined && (
                          <Col xs={24} sm={8}>
                              <Card size="small" style={{ textAlign: 'center' }}>
                                  <div style={{ marginBottom: 8 }}>
                                      <Link size={24} style={{ color: catalogDetail.dorisConnected ? '#52c41a' : '#ff4d4f' }} />
                                  </div>
                                  <Text strong>Doris连接</Text>
                                  <div style={{ marginTop: 4 }}>
                                      <Tag color={catalogDetail.dorisConnected ? 'success' : 'error'}>
                                          {catalogDetail.dorisConnected ? '成功' : '失败'}
                                      </Tag>
                                  </div>
                                  {catalogDetail.dorisConnectedDt && (
                                      <div style={{ marginTop: 4 }}>
                                          <Text type="secondary" style={{ fontSize: 11 }}>
                                              <Clock size={10} style={{ marginRight: 2 }} />
                                              {catalogDetail.dorisConnectedDt}
                                          </Text>
                                      </div>
                                  )}
                                  <Button
                                      icon={<Link size={14} />}
                                      onClick={async () => {
                                          const ok = await testConnection(catalogName, 'doris')
                                          notify(ok ? 'Doris连接成功' : 'Doris连接失败', ok ? 'success' : 'error')
                                      }}
                                  >
                                      测试Doris
                                  </Button>
                              </Card>
                          </Col>
                      )}
                  </Row>
              </div>
            {/* 基本信息 */}
            <div>
              <Title level={5} style={{ color: '#1d2129', marginBottom: 12 }}>
                <Server size={16} style={{ marginRight: 6 }} />
                基本信息
              </Title>
              <Descriptions column={{ xs: 1, sm: 2, md: 3 }} size="small" bordered>
                <Descriptions.Item label={<><Database size={12} style={{ marginRight: 4 }} />目录名</>}>
                  {catalogDetail.catalogName}
                </Descriptions.Item>
                <Descriptions.Item label={<><Server size={12} style={{ marginRight: 4 }} />主机</>}>
                  {catalogDetail.host}
                </Descriptions.Item>
                <Descriptions.Item label="端口">{catalogDetail.port}</Descriptions.Item>
                <Descriptions.Item label="数据库类型">
                  <Tag color="blue">{catalogDetail.databaseType}</Tag>
                </Descriptions.Item>
                <Descriptions.Item label={<><User size={12} style={{ marginRight: 4 }} />用户名</>}>
                  {catalogDetail.userName}
                </Descriptions.Item>
                <Descriptions.Item label="连接类型">
                  <Tag color="green">{catalogDetail.connectType}</Tag>
                </Descriptions.Item>
                {catalogDetail.databaseVersion !== undefined && (
                  <Descriptions.Item label="数据库版本">{catalogDetail.databaseVersion}</Descriptions.Item>
                )}
                <Descriptions.Item label="Doris目录名">{catalogDetail.dorisCatalogName}</Descriptions.Item>
                <Descriptions.Item label={<><Code size={12} style={{ marginRight: 4 }} />默认系统码</>}>
                  {catalogDetail.defaultSystemCode}
                </Descriptions.Item>
                <Descriptions.Item label="启用状态">
                  {catalogDetail.enabled ? (
                    <Tag color="success" icon={<CheckCircle size={12} />}>已启用</Tag>
                  ) : (
                    <Tag color="error" icon={<XCircle size={12} />}>已禁用</Tag>
                  )}
                </Descriptions.Item>
                  <Title level={5} style={{ color: '#1d2129', marginBottom: 12 }}>
                      <Link size={16} style={{ marginRight: 6 }} />
                      连接路由
                  </Title>
                  <Card size="small" style={{ background: '#fafbfc' }}>
                      <Text code copyable style={{ wordBreak: 'break-all' }}>
                          {catalogDetail.route}
                      </Text>
                  </Card>
              </Descriptions>
            </div>
          </div>
        ) : (
          <Empty
            image={<Database size={48} style={{ color: '#c9cdd4' }} />}
            description={
              <div>
                <Text type="secondary">暂无目录详情</Text>
                <br />
                <Text type="secondary" style={{ fontSize: 12 }}>
                  请检查网络连接或联系管理员
                </Text>
              </div>
            }
          />
        )}
      </Card>
    </div>
  )
}

export default CatalogPanel